/**
 * @Author: jichang
 * @Date: 2024/10/31 17:09:30
 * @LastEditors: jichang
 * @LastEditTime: 2024/10/31 17:09:30
 * Description: 原子操作从队列中读取数据
 */
#include <atomic>
#include <thread>
#include <vector>
#include <iostream>

std::vector<int> queue_data;
std::atomic<int> count;

void populate_queue() {
    unsigned const number_of_items = 20;
    queue_data.clear();
    for (unsigned i = 0; i < number_of_items; ++i) {
        queue_data.push_back(i);
    }
    // 把总数存储到原子count
    count.store(number_of_items, std::memory_order_release);
}
void wait_for_more_items();
void process(int a);

// count: release存储并且acquire读取，所以存储与加载同步，线程可以从缓存中读取元素
void consume_queue_items() {
    while (true) {
        int item_index;
        // 这里会产生两个线程的竞争 fetch_sub
        if ((item_index = count.fetch_sub(1, std::memory_order_acquire)) <= 0) {
            wait_for_more_items();
            continue;
        }
        process(queue_data[item_index-1]);
    }
}

int main(int argc, char const *argv[])
{
    std::thread a(populate_queue);
    std::thread b(consume_queue_items);
    std::thread c(consume_queue_items);

    a.join();
    b.join();
    c.join();
    
    return 0;
}



